import rainImg from './rain.png';
export default class Rain {
	constructor(
		viewer,
		position,
		snowParticleSize = 12,
		startScale = 0.5,
		endScale = 1,
		number = 7000
	) {
		this.viewer = viewer;
		this.rainSystem = null;
		this.snowParticleSize = snowParticleSize;
		this.startScale = startScale;
		this.endScale = endScale;
		this.number = number;
	}

	show() {
		var planePosition = Cesium.Cartesian3.fromDegrees(
			116.3795982453785,
			39.963036292028164,
			500
		);
		var particlesOffset = new Cesium.Cartesian3(0, 0, 0);

		var translationOffset = Cesium.Matrix4.fromTranslation(
			particlesOffset,
			new Cesium.Matrix4()
		);
		var translationOfPlane = Cesium.Matrix4.fromTranslation(
			planePosition,
			new Cesium.Matrix4()
		);

		var particlesModelMatrix = Cesium.Matrix4.multiplyTransformation(
			translationOfPlane,
			translationOffset,
			new Cesium.Matrix4()
		);
		var snowParticleSize = 10.0;
		var snowRadius = 1000.0;
		var minimumSnowImageSize = new Cesium.Cartesian2(
			snowParticleSize * 0.1,
			snowParticleSize * 1
		);
		var maximumSnowImageSize = new Cesium.Cartesian2(
			snowParticleSize * 0.3,
			snowParticleSize * 4
		);
		var rainSystem;

		var snowGravityScratch = new Cesium.Cartesian3();
		var snowUpdate = function (particle, dt) {
			snowGravityScratch = Cesium.Cartesian3.normalize(
				particle.position,
				snowGravityScratch
			);
			Cesium.Cartesian3.multiplyByScalar(
				snowGravityScratch,
				Cesium.Math.randomBetween(-10, -10),
				snowGravityScratch
			);
			particle.velocity = Cesium.Cartesian3.add(
				particle.velocity,
				snowGravityScratch,
				particle.velocity
			);

			var distance = Cesium.Cartesian3.distance(
				planePosition,
				particle.position
			);
			if (distance > snowRadius) {
				particle.endColor.alpha = 0.0;
			} else {
				particle.endColor.alpha =
					rainSystem.endColor.alpha / (distance / snowRadius + 0.1);
			}
		};

		rainSystem = new Cesium.ParticleSystem({
			modelMatrix: particlesModelMatrix,
			minimumSpeed: 0.1,
			maximumSpeed: 0.5,
			lifetime: 15.0,
			emitter: new Cesium.BoxEmitter(
				new Cesium.Cartesian3(5000.0, 2000.0, 5000)
			),
			// emitter: new Cesium.SphereEmitter(snowRadius),
			startScale: 0.5,
			endScale: 1.0,
			image: rainImg,
			emissionRate: 6000.0,
			startColor: new Cesium.Color(0.8, 0.8, 0.8, 0.0),
			endColor: new Cesium.Color(0.8, 0.8, 0.8, 0.98),
			minimumImageSize: minimumSnowImageSize,
			maximumImageSize: maximumSnowImageSize,
			updateCallback: snowUpdate,
		});
		this.viewer.addPrimitive('rain', rainSystem);
	}

	changeShow(isShow) {
		this.viewer.changePrimitiveShow('rain', isShow);
	}

	remove() {
		this.viewer.removePrimitive('rain');
	}
}
